package de.idgard.json.transport;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;

/**
 * 
 * @author <a href="mailto:vesko.georgiev@uniscon.com">Vesko Georgiev</a>
 */
public class IDGHttpClient extends DefaultHttpClient {

	private String idgardHost;

	public IDGHttpClient(String idgardHost) {
		this.idgardHost = idgardHost;
		addResponseInterceptor(createResponseInterceptor());
		addRequestInterceptor(createRequestInterceptor());
	}

	protected HttpResponseInterceptor createResponseInterceptor() {
		return new HttpResponseInterceptor() {
			@Override
			public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					Header ceheader = entity.getContentEncoding();
					if (ceheader != null) {
						HeaderElement[] codecs = ceheader.getElements();

						for (int i = 0; i < codecs.length; i++) {
							if (codecs[i].getName().equalsIgnoreCase("gzip")) {
								response.setEntity(new GzipDecompressingEntity(response.getEntity()));
								return;
							}
						}
					}
				}
			}
		};
	}

	protected HttpRequestInterceptor createRequestInterceptor() {
		return new HttpRequestInterceptor() {
			@Override
			public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
				request.setHeader("Content-Type", "application/json;charset=UTF-8");
				request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				request.setHeader("Accept-Encoding", "gzip, deflate");
				request.setHeader("Accept-Language", "en-us,en;q=0.5");
				request.setHeader("Cache-Control", "no-cache");
				request.setHeader("Connection", "keep-alive");
				request.setHeader("Host", idgardHost);
				request.setHeader("Pragma", "no-cache");
			}
		};
	}

	public void onPreExecute() {
		//
	}

	protected class GzipDecompressingEntity extends HttpEntityWrapper {

		public GzipDecompressingEntity(final HttpEntity entity) {
			super(entity);
		}

		@Override
		public InputStream getContent() throws IOException, IllegalStateException {
			InputStream wrappedin = wrappedEntity.getContent();
			return new GZIPInputStream(wrappedin);
		}

		@Override
		public long getContentLength() {
			return -1;
		}
	}
}
